/*
 * Copyright 2002-2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.elancom.framework.web.tags.form;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.jsp.JspException;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * Abstract base class to provide common methods for implementing databinding-aware JSP tags for rendering <i>multiple</i> HTML '<code>input</code>' elements
 * with a '<code>type</code>' of '<code>checkbox</code>' or '<code>radio</code>'.
 * 
 * @author Juergen Hoeller
 * @author Scott Andrews
 * @since 2.5.2
 */
public abstract class AbstractMultiCheckedElementTag extends AbstractCheckedElementTag {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7050092849572819581L;

	/**
	 * The HTML '<code>span</code>' tag.
	 */
	private static final String SPAN_TAG = "span";

	/**
	 * The {@link java.util.Collection}, {@link java.util.Map} or array of objects used to generate the '<code>input type="checkbox/radio"</code>' tags.
	 */
	private Object items;

	/**
	 * The name of the property mapped to the '<code>value</code>' attribute of the '<code>input type="checkbox/radio"</code>' tag.
	 */
	private String itemValue;

	/**
	 * The value to be displayed as part of the '<code>input type="checkbox/radio"</code>' tag.
	 */
	private String itemLabel;

	/**
	 * The HTML element used to enclose the '<code>input type="checkbox/radio"</code>' tag.
	 */
	private String element = SPAN_TAG;

	/**
	 * Delimiter to use between each '<code>input type="checkbox/radio"</code>' tags.
	 */
	private String delimiter;

	/**
	 * Set the {@link java.util.Collection}, {@link java.util.Map} or array of objects used to generate the '<code>input type="checkbox/radio"</code>' tags.
	 * <p>
	 * Typically a runtime expression.
	 * 
	 * @param items
	 *            said items
	 */
	public void setItems(Object items) {
		Assert.notNull(items, "'items' must not be null");
		this.items = items;
	}

	/**
	 * Get the {@link java.util.Collection}, {@link java.util.Map} or array of objects used to generate the '<code>input type="checkbox/radio"</code>' tags.
	 */
	protected Object getItems() {
		return items;
	}

	/**
	 * Set the name of the property mapped to the '<code>value</code>' attribute of the '<code>input type="checkbox/radio"</code>' tag.
	 * <p>
	 * May be a runtime expression.
	 */
	public void setItemValue(String itemValue) {
		Assert.hasText(itemValue, "'itemValue' must not be empty");
		this.itemValue = itemValue;
	}

	/**
	 * Get the name of the property mapped to the '<code>value</code>' attribute of the '<code>input type="checkbox/radio"</code>' tag.
	 */
	protected String getItemValue() {
		return itemValue;
	}

	/**
	 * Set the value to be displayed as part of the '<code>input type="checkbox/radio"</code>' tag.
	 * <p>
	 * May be a runtime expression.
	 */
	public void setItemLabel(String itemLabel) {
		Assert.hasText(itemLabel, "'itemLabel' must not be empty");
		this.itemLabel = itemLabel;
	}

	/**
	 * Get the value to be displayed as part of the '<code>input type="checkbox/radio"</code>' tag.
	 */
	protected String getItemLabel() {
		return itemLabel;
	}

	/**
	 * Set the delimiter to be used between each '<code>input type="checkbox/radio"</code>' tag.
	 * <p>
	 * By default, there is <em>no</em> delimiter.
	 */
	public void setDelimiter(String delimiter) {
		this.delimiter = delimiter;
	}

	/**
	 * Return the delimiter to be used between each '<code>input type="radio"</code>' tag.
	 */
	public String getDelimiter() {
		return delimiter;
	}

	/**
	 * Set the HTML element used to enclose the '<code>input type="checkbox/radio"</code>' tag.
	 * <p>
	 * Defaults to an HTML '<code>&lt;span/&gt;</code>' tag.
	 */
	public void setElement(String element) {
		Assert.hasText(element, "'element' cannot be null or blank");
		this.element = element;
	}

	/**
	 * Get the HTML element used to enclose '<code>input type="checkbox/radio"</code>' tag.
	 */
	public String getElement() {
		return element;
	}

	/**
	 * Appends a counter to a specified id as well, since we're dealing with multiple HTML elements.
	 */
	@Override
	protected String resolveId() throws JspException {
		final Object id = evaluate("id", getId());
		if (id != null) {
			final String idString = id.toString();
			return (StringUtils.hasText(idString) ? TagIdGenerator.nextId(idString, pageContext) : null);
		}
		return autogenerateId();
	}

	/**
	 * Renders the '<code>input type="radio"</code>' element with the configured {@link #setItems(Object)} values. Marks the element as checked if the value
	 * matches the bound value.
	 */
	@SuppressWarnings("rawtypes")
	@Override
	protected int writeTagContent(TagWriter tagWriter) throws JspException {
		final Object items = getItems();
		Object itemsObject = (items instanceof String ? evaluate("items", items) : items);

		final String itemValue = getItemValue();
		final String itemLabel = getItemLabel();
		final String valueProperty = (itemValue != null ? ObjectUtils.getDisplayString(evaluate("itemValue", itemValue)) : null);
		final String labelProperty = (itemLabel != null ? ObjectUtils.getDisplayString(evaluate("itemLabel", itemLabel)) : null);

		final Class<?> boundType = getBindStatus().getValueType();
		if (itemsObject == null && boundType != null && boundType.isEnum()) {
			itemsObject = boundType.getEnumConstants();
		}

		if (itemsObject == null) {
			throw new IllegalArgumentException("Attribute 'items' is required and must be a Collection, an Array or a Map");
		}

		if (itemsObject.getClass().isArray()) {
			final Object[] itemsArray = (Object[]) itemsObject;
			for (int i = 0; i < itemsArray.length; i++) {
				final Object item = itemsArray[i];
				writeObjectEntry(tagWriter, valueProperty, labelProperty, item, i);
			}
		} else if (itemsObject instanceof Collection) {
			final Collection optionCollection = (Collection) itemsObject;
			int itemIndex = 0;
			for (final Iterator it = optionCollection.iterator(); it.hasNext(); itemIndex++) {
				final Object item = it.next();
				writeObjectEntry(tagWriter, valueProperty, labelProperty, item, itemIndex);
			}
		} else if (itemsObject instanceof Map) {
			final Map optionMap = (Map) itemsObject;
			int itemIndex = 0;
			for (final Iterator it = optionMap.entrySet().iterator(); it.hasNext(); itemIndex++) {
				final Map.Entry entry = (Map.Entry) it.next();
				writeMapEntry(tagWriter, valueProperty, labelProperty, entry, itemIndex);
			}
		} else {
			throw new IllegalArgumentException("Attribute 'items' must be an array, a Collection or a Map");
		}

		return SKIP_BODY;
	}

	private void writeObjectEntry(TagWriter tagWriter, String valueProperty, String labelProperty, Object item, int itemIndex) throws JspException {

		final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
		Object renderValue;
		if (valueProperty != null) {
			renderValue = wrapper.getPropertyValue(valueProperty);
		} else if (item instanceof Enum) {
			renderValue = ((Enum<?>) item).name();
		} else {
			renderValue = item;
		}
		final Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
		writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
	}

	private void writeMapEntry(TagWriter tagWriter, String valueProperty, String labelProperty, @SuppressWarnings("rawtypes") Map.Entry entry, int itemIndex)
			throws JspException {

		final Object mapKey = entry.getKey();
		final Object mapValue = entry.getValue();
		final BeanWrapper mapKeyWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapKey);
		final BeanWrapper mapValueWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapValue);
		final Object renderValue = (valueProperty != null ? mapKeyWrapper.getPropertyValue(valueProperty) : mapKey.toString());
		final Object renderLabel = (labelProperty != null ? mapValueWrapper.getPropertyValue(labelProperty) : mapValue.toString());
		writeElementTag(tagWriter, mapKey, renderValue, renderLabel, itemIndex);
	}

	private void writeElementTag(TagWriter tagWriter, Object item, Object value, Object label, int itemIndex) throws JspException {

		tagWriter.startTag(getElement());
		if (itemIndex > 0) {
			final Object resolvedDelimiter = evaluate("delimiter", getDelimiter());
			if (resolvedDelimiter != null) {
				tagWriter.appendValue(resolvedDelimiter.toString());
			}
		}
		tagWriter.startTag("input");
		final String id = resolveId();
		writeOptionalAttribute(tagWriter, "id", id);
		writeOptionalAttribute(tagWriter, "name", getName());
		writeOptionalAttributes(tagWriter);
		tagWriter.writeAttribute("type", getInputType());
		renderFromValue(item, value, tagWriter);
		tagWriter.endTag();
		tagWriter.startTag("label");
		tagWriter.writeAttribute("for", id);
		tagWriter.appendValue(convertToDisplayString(label));
		tagWriter.endTag();
		tagWriter.endTag();
	}

}
